package wat.serwerapp.admins;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import wat.ziszcommon.invoker.Method;
import wat.serwerapp.usermgmt.ldap.RoleManager;
import wat.serwerapp.usermgmt.UserManager;
import wat.serwerapp.usermgmt.UserManager.User;

/**
 *
 * @author P.B. & L.G. & K.K.
 */
public class GetUsersList implements Method {

   private static Set<String> owners;

   public Set<String> getOwners() {
      if (owners == null) {
         owners = new HashSet<String>();
         owners.add("pl.edu.wat.erp.client.administration.UserAdministrationClient");
      }
      return owners;
   }

   // username:role,role,role;username:role,role
   public String invoke(String parameters) {
      try {
         String response = "";
         Set<User> users = UserManager.getAllUsers();
         for (User user : users) {
            // Manager - superuser
            if (!user.getName().equals("Manager")) {
               System.out.println("USER:" + user.getName());
               response = response + user.getName() + ":";
               Set<String> roles = user.getRoles();
               for (String role : roles) {
                  System.out.println("ROLE:" + role);
                  String tmpRole = RoleManager.roleFromLdapFormat(role);
                  System.out.println("ROLE:" + tmpRole);
                  response = response + tmpRole + ",";
               }
               if (response.lastIndexOf(",") == response.length() - 1) {
                  response = response.substring(0, response.length() - 1);
               }
               response = response + ";";
            }
         }
         if (response.lastIndexOf(";") == response.length() - 1) {
            response = response.substring(0, response.length() - 1);
         }
         System.out.println("RESPONSE:");
         System.out.println(response);
         return response;
      } catch (NamingException ex) {
         Logger.getLogger(GetUsersList.class.getName()).log(Level.SEVERE, null, ex);
      }
      return null;
   }

   // zwraca TYLKO liste uzytkownikow - bez uprawnien
   public List invoke(List parameters) {
      try {
         ArrayList list = new ArrayList();
         Set<User> users = UserManager.getAllUsers();
         for (User user : users) {
            // Manager - superuser
            if (!user.getName().equals("Manager")) {
               System.out.println("USER:" + user.getName());
               list.add(user.getName());
            }
         }
         return list;
      } catch (NamingException ex) {
         Logger.getLogger(GetUsersList.class.getName()).log(Level.SEVERE, null, ex);
      }
      return null;
   }
}
